export function randomInt(a: number, b?: number) {
    const start = b ? a : 0
    const end = b ?? a
    return Math.trunc(Math.random() * (end - start) + start)
}

/** 用于Array.sort的参数，可以将数组随机排序 */
export function randomSort() {
    return Math.random() - 0.5
}

0 /** 从数组中随机选取N个值，返回的数组中的每个值都是在源数组中不同位置选取的，返回的数组中是否有重复的值取决于源数组是否有重复的值 */
export function randomSelect<T>(array: T[], quantity: number): T[] {
    if (quantity < 1) return []
    if (quantity > array.length) throw "quantity > array.length"

    const indexArray: number[] = []
    while (indexArray.length < quantity) {
        const randomIndex = randomInt(array.length)
        if (!indexArray.includes(randomIndex)) indexArray.push(randomIndex)
    }

    const r: T[] = []
    indexArray.forEach((i) => r.push(array[i]))
    return r
}

export function never(x: never) {
    x
}

// Convert number to words

import { ToWords } from "to-words"

const toWords = new ToWords({
    localeCode: "en-US",
})

export function numberToWords(num: number) {
    return toWords.convert(num)
}

export function replaceNumbersWithWords(str: string) {
    const regex = /[0-9]+/g
    const found = str.match(regex)
    let r = str
    if (!found) {
        return r
    } else {
        for (const n of found) {
            const words = numberToWords(parseInt(n))
            r = r.replace(n, words)
        }
    }
    return r
}

export function unproxy<T>(t: T): T {
    if (typeof t === "object") {
        // if (Array.isArray(t)) {
        // return [...t] as T
        // }
        const obj = { ...t }
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                obj[key] = unproxy(obj[key])
            }
        }
        return obj
    } else {
        return t
    }
}

export function toArray<T>(arrOrObject: Array<T>): Array<T> {
    if (Array.isArray(arrOrObject)) {
        return arrOrObject
    } else {
        const r: T[] = []
        for (const key in arrOrObject as any) {
            if (Object.prototype.hasOwnProperty.call(arrOrObject, key)) {
                const element = arrOrObject[key]
                r.push(element)
            }
        }
        return r
    }
}
